import Vue from 'vue'
import Vuex from 'vuex'
import * as types from './mutations-types'

Vue.use(Vuex);

export default new Vuex.Store({
  namespaced: true,
  state: {
    get currentUser() {
      return JSON.parse(window.localStorage.getItem('STORE')) || {}
    },
    get registerRecord() {
      return JSON.parse(window.localStorage.getItem('registerRecord')) || {}
    },
    get isFirst() {
      //默认为true
      return window.localStorage.getItem('isFirst') || 'true'
    }
  },
  mutations: {
    [types.SET_USER](state, {member_id, tel, token, name, member_number, image}) {
      let STORE = window.localStorage.getItem('STORE');
      if (!STORE) STORE = {};
      else STORE = JSON.parse(STORE);
      if (member_id) STORE.member_id = member_id;
      if (tel) STORE.tel = tel;
      if (token) STORE.token = token;
      if (name) STORE.name = name;
      if (member_number) STORE.member_number = member_number;
      if (image) STORE.image = image;
      window.localStorage.setItem('STORE', JSON.stringify(STORE));
    },
    [types.SET_REGISTER](state, {tel, member_id, type, token}) {
      let record = window.localStorage.getItem('registerRecord');
      if (!record) record = {};
      else record = JSON.parse(record);
      if (type) record.type = type;
      if (token) record.token = token;
      if (tel) record.tel = tel;
      if (member_id) record.member_id = member_id;
      window.localStorage.setItem('registerRecord', JSON.stringify(record));
    },
    [types.REMOVE_REGISTER]() {
      window.localStorage.removeItem('registerRecord');
    },
    [types.LOGOUT]() {
      window.localStorage.removeItem('STORE');
    },
    [types.SET_ISFIRST](state, val) {
      //val true则是第一次 false 不是 用户为注册状态不算
      if (val !== 'undefined' && val !== null) {
        window.localStorage.setItem('isFirst', val);
      }
    }
  }
});
